package com.huiminpay.merchant.service.impl;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private String smsEffectiveTime;
    @Override
    public String sendSms(String phone) {
        String url=smsUrl+"/generate?effectiveTime=600&name=sms";//+smsEffectiveTime
        Map<String, Object> body = new HashMap<>();
        body.put("mobile",phone);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body,httpHeaders);
        ResponseEntity<Map> forEntity = null;
        try {
            forEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        Map responBody = forEntity.getBody();
        if (responBody==null||responBody.get("result")==null){
            throw new RuntimeException("发送验证码错误");
        }
        Map result = (Map)responBody.get("result");
        String value = result.get("key").toString();
        return value;
    }
    @Override
    public void verifyCode(String verficationKey,String verifyCode ) {
        String url=smsUrl+"/verify?name=sms&verificationKey="+verficationKey+"&verificationCode="+verifyCode;//+smsEffectiveTime


        ResponseEntity<Map> forEntity = null;
        try {
            forEntity = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
        } catch (RestClientException e) {
            log.info(e.getMessage(),e);
            throw new BusinessException(CommonErrorCode.E_100102);
        }
        Map responBody = forEntity.getBody();
        if (responBody==null||responBody.get("result")==null||!(boolean)responBody.get("result")){
            throw new BusinessException(CommonErrorCode.E_100102);
        }
    }
}
